package com.liy.cloud.auth.client.aop;

import com.liy.cloud.auth.client.jwt.JwtTokenService;
import com.liy.framework.common.annotation.ActionPermission;
import com.liy.framework.common.annotation.IgnoreUserToken;
import com.liy.framework.common.annotation.MethodPermission;
import com.liy.framework.common.extvo.LoginInfo;
import com.liy.framework.common.utils.ContextHandler;
import com.liy.framework.common.utils.Tools;
import com.liy.framework.common.web.exception.InvalidRequestException;
import com.liy.framework.common.web.exception.NoAuthorizationException;
import com.liy.framework.common.web.utils.AopTargetUtils;
import com.liy.framework.common.web.utils.WebTools;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


@Component
public class AuthorizationInterceptorService extends HandlerInterceptorAdapter {
    private static Logger log = LoggerFactory.getLogger(AuthorizationInterceptorService.class);

    @Value("${dascloud.authrization.enabled: true}")
    private Boolean authrizationEnabled;

    @Value("${dascloud.authrization.token-header:JwtToken}")
    private String tokenHeader;

    @Value("${dascloud.authrization.auth-key:AuthKey}")
    private String authKeyHeader;

    @Autowired
    private JwtTokenService jwtTokenService;

    public AuthorizationInterceptorService() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("new request: " + request.getRequestURL());
        if (request.getRequestURL().toString().contains("get/rou")) {
            System.out.println("111");
        }

        if (!(handler instanceof HandlerMethod)) {
            throw new InvalidRequestException("无效的请求 [ " + request.getRequestURL().toString() + " ] ");
        } else if (!this.authrizationEnabled) {
            return super.preHandle(request, response, handler);
        } else {
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            IgnoreUserToken annotation = (IgnoreUserToken)handlerMethod.getBeanType().getAnnotation(IgnoreUserToken.class);
            if (annotation == null) {
                annotation = (IgnoreUserToken)handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
            }

            if (annotation != null) {
                return super.preHandle(request, response, handler);
            } else {
                String authKey = WebTools.getRequesetParameterOrHeader(request, this.authKeyHeader);
                String jwtToken = WebTools.getRequesetParameterOrHeader(request, this.tokenHeader);
                if (Tools.StringIsNullOrSpace(jwtToken)) {
                    throw new NoAuthorizationException("未认证的请求.");
                } else {
                    LoginInfo loginInfo = this.jwtTokenService.getInfoFromToken(jwtToken);
                    ContextHandler.setLoginUser(loginInfo);
                    ContextHandler.setJwtToken(jwtToken);
                    ContextHandler.setAuthKey(authKey);
                    return super.preHandle(request, response, handler);
                }
            }
        }
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }

    private StringBuffer getPermissionCodes(Object handler) throws Exception {
        StringBuffer permissionBuffer = null;
        HandlerMethod method = (HandlerMethod)handler;
        Class<?> clazz = AopTargetUtils.getTarget(method.getBean()).getClass();
        ActionPermission actionPermission = (ActionPermission)clazz.getAnnotation(ActionPermission.class);
        if (actionPermission != null && !Tools.StringIsNullOrSpace(actionPermission.code())) {
            MethodPermission methodPermission = (MethodPermission)method.getMethodAnnotation(MethodPermission.class);
            if (methodPermission != null && methodPermission.codes() != null && methodPermission.codes().length > 0) {
                permissionBuffer = new StringBuffer();
                String[] var7 = methodPermission.codes();
                int var8 = var7.length;

                for(int var9 = 0; var9 < var8; ++var9) {
                    String code = var7[var9];
                    permissionBuffer.append(actionPermission.code()).append("&").append(code).append(";");
                }
            }
        }

        return permissionBuffer;
    }
}
